var goods_id = getQueryString("groupbuy_id");
var my_store_id = getQueryString('mystore_id');
var map_list = [];
var map_index_id = '';
var store_id;
var g_goods_id;
$(function (){
    var key = getCookie('key');

    var unixTimeToDateString = function(ts, ex) {
        ts = parseFloat(ts) || 0;
        if (ts < 1) {
            return '';
        }
        var d = new Date();
        d.setTime(ts * 1e3);
        var s = '' + d.getFullYear() + '-' + (1 + d.getMonth()) + '-' + d.getDate();
        if (ex) {
            s += ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
        }
        return s;
    };

    var buyLimitation = function(a, b) {
        a = parseInt(a) || 0;
        b = parseInt(b) || 0;
        var r = 0;
        if (a > 0) {
            r = a;
        }
        if (b > 0 && r > 0 && b < r) {
            r = b;
        }
        return r;
    };

    template.helper('isEmpty', function(o) {
        for (var i in o) {
            return false;
        }
        return true;
    });

     // 图片轮播
    function picSwipe(){
      var elem = $("#mySwipe")[0];
      window.mySwipe = Swipe(elem, {
        continuous: false,
        // disableScroll: true,
        stopPropagation: true,
        callback: function(index, element) {
          $('.goods-detail-turn').find('li').eq(index).addClass('cur').siblings().removeClass('cur');
        }
      });
    }
    get_detail(goods_id);
  //点击商品规格，获取新的商品
  function arrowClick(self,myData){
    $(self).addClass("current").siblings().removeClass("current");
    //拼接属性
    var curEle = $(".spec").find("a.current");
    var curSpec = [];
    $.each(curEle,function (i,v){
        // convert to int type then sort
        curSpec.push(parseInt($(v).attr("specs_value_id")) || 0);
    });
    var spec_string = curSpec.sort(function(a, b) { return a - b; }).join("|");
    //获取商品ID
    goods_id = myData.spec_list[spec_string];
    get_detail(goods_id);
  }

  function contains(arr, str) {//检测goods_id是否存入
	    var i = arr.length;
	    while (i--) {
           if (arr[i] === str) {
	           return true;
           }
	    }
	    return false;
	}
  $.sValid.init({
        rules:{
            buynum:"digits"
        },
        messages:{
            buynum:"请输入正确的数字"
        },
        callback:function (eId,eMsg,eRules){
            if(eId.length >0){
                var errorHtml = "";
                $.map(eMsg,function (idx,item){
                    errorHtml += "<p>"+idx+"</p>";
                });
                $.sDialog({
                    skin:"red",
                    content:errorHtml,
                    okBtn:false,
                    cancelBtn:false
                });
            }
        }
    });
  //检测商品数目是否为正整数
  function buyNumer(){
    $.sValid();
  }
  function get_detail(goods_id) {
      //渲染页面
      $.ajax({
         url:ApiUrl+"/index.php?act=goods&op=groupbyshow",
         type:"get",
         data:{group_id:goods_id,key:key},
         dataType:"json",
         success:function(result){
            var data = result.datas;
            if(!data.error){
              //商品图片格式化数据
              if(data.goods_image){
                var goods_image = data.goods_image.split(",");
                data.goods_image = goods_image;
              }else{
                 data.goods_image = [];
              }
                data.groupbuy_info.all_buy_quantity = parseInt(data.groupbuy_info.buy_quantity)+parseInt(data.groupbuy_info.virtual_quantity)
              //渲染模板
              g_goods_id = data.groupbuy_info.goods_id;
              var html = template.render('product_detail', data);
              $("#product_detail_html").html(html);


              // 倒计时开始
              if(data.groupbuy_info.count_down)  {
                  cutDown(data.groupbuy_info.count_down);
              }

              // 购物车中商品数量
              if (getCookie('cart_count')) {
                  if (getCookie('cart_count') > 0) {
                      $('#cart_count,#cart_count1').html('<sup>'+getCookie('cart_count')+'</sup>');
                  }
              }

              //图片轮播
              picSwipe();
              //商品描述
              $(".pddcp-arrow").click(function (){
                $(this).parents(".pddcp-one-wp").toggleClass("current");
              });
              //规格属性
              var myData = {};
              myData["spec_list"] = data.spec_list;
              $(".spec a").click(function (){
                var self = this;
                arrowClick(self,myData);
              });
              //购买数量，减
              $(".minus").click(function (){
                 var buynum = $(".buy-num").val();
                 if(buynum >1){
                    $(".buy-num").val(parseInt(buynum-1));
                 }
              });
              //购买数量加
              $(".add").click(function (){
                 var buynum = parseInt($(".buy-num").val());
                 if(buynum < data.goods_info.goods_storage){
                    $(".buy-num").val(parseInt(buynum+1));
                 }
              });

              //收藏
              $(".pd-collect").click(function (){
                  if ($(this).hasClass('favorate')) {
                      if (dropFavoriteGoods(goods_id)) $(this).removeClass('favorate');
                  } else {
                      if (favoriteGoods(goods_id)) $(this).addClass('favorate');
                  }
              });


            }else {

              $.sDialog({
                  content: data.error + '！<br>请返回上一页继续操作…',
                  okBtn:false,
                  cancelBtnText:'返回',
                  cancelFn: function() { history.back(); }
              });
            }

            //验证购买数量是不是数字
            $("#buynum").blur(buyNumer);
            

            // 从下到上动态显示隐藏内容
            $.animationUp({
                valve : '.animation-up,#goods_spec_selected',          // 动作触发
                wrapper : '#product_detail_spec_html',    // 动作块
                scroll : '#product_roll',     // 滚动块，为空不触发滚动
                start : function(){       // 开始动作触发事件
                    $('.goods-detail-foot').addClass('hide').removeClass('block');
                },
                close : function(){        // 关闭动作触发事件
                    $('.goods-detail-foot').removeClass('hide').addClass('block');
                }
            });
            
            $.animationUp({
                valve : '#getVoucher',          // 动作触发
                wrapper : '#voucher_html',    // 动作块
                scroll : '#voucher_roll',     // 滚动块，为空不触发滚动
            });

            $('#voucher_html').on('click', '.btn', function(){
                getFreeVoucher($(this).attr('data-tid'));
            });
            
            // 联系客服
            $('.kefu').click(function(){
                window.location.href = WapSiteUrl+'/tmpl/member/chat_info.html?goods_id=' + goods_id + '&t_id=' + result.datas.store_info.member_id;
            })
         }
      });
  }
  
  $.scrollTransparent();
  $('#product_detail_html').on('click', '#get_area_selected', function(){
      $.areaSelected({
          success : function(data){
              $('#get_area_selected_name').html(data.area_info);
              var area_id = data.area_id_2 == 0 ? data.area_id_1:data.area_id_2;
              $.getJSON(ApiUrl + '/index.php?act=goods&op=calc', {goods_id:goods_id,area_id:area_id},function(result){
                  $('#get_area_selected_whether').html(result.datas.if_store_cn);
                  $('#get_area_selected_content').html(result.datas.content);
                  if (!result.datas.if_store) {
                      $('.buy-handle').addClass('no-buy');
                  } else {
                      $('.buy-handle').removeClass('no-buy');
                  }
              });
          }
      });
  });

  $('body').on('click', '#goodsBody,#goodsBody1', function(){
      window.location.href = WapSiteUrl+'/tmpl/product_info.html?goods_id=' + g_goods_id;
  });
  $('body').on('click', '#goodsEvaluation,#goodsEvaluation1', function(){
      window.location.href = WapSiteUrl+'/tmpl/product_eval_list.html?goods_id=' + g_goods_id;
  });

});

/**
 * 到计时
 */
function cutDown(time){
     var timer = null;
     var day, h, m, s,remain; // 天 /时 / 分 / 秒
     var timeSpan = document.getElementsByClassName('time')[0].getElementsByTagName('span');
     timer = setInterval(function(){
          time--;
          if (time==0){
               $("#buy").remove();
               $(".groupby_price").append("<span id='end'>已结束</span>");
               $(".time").hide();
               $(".timeend").show();
               clearInterval(timer);
          }
          day = fill_zero(parseInt(time/(3600*24)));
          remain = time%(3600*24);
          h = fill_zero(parseInt(remain/3600));
          remain = remain%3600;
          m = fill_zero(parseInt(remain/60));
          remain = parseInt(remain%60);
          s = fill_zero(remain);
          timeSpan[0].innerHTML = day;
          timeSpan[1].innerHTML = h;
          timeSpan[2].innerHTML = m;
          timeSpan[3].innerHTML = s;
     },1000)
}

//补零函数
function fill_zero(num){
    if(num<=9){

        return "0"+num;

    }else{
        return ""+num;
    }
}